Page({
  data: {
    planList: [],
    selectedPlan: null,
    selectedPlanIndex: 0,
    planSchedules: [],
    userId: 1 // TODO: 替换为实际登录用户id
  },
  onLoad() {
    this.loadPlans();
  },
  loadPlans() {
    wx.request({
      url: getApp().globalData.baseUrl + '/api/ride/plan/list',
      data: { userId: this.data.userId },
      success: res => {
        const planList = res.data.data || [];
        this.setData({ planList });
        if (planList.length > 0) {
          this.setData({ selectedPlan: planList[0], selectedPlanIndex: 0 });
          this.loadPlanSchedules(planList[0]);
        }
      }
    });
  },
  onPlanPickerChange(e) {
    const idx = Number(e.detail.value);
    const plan = this.data.planList[idx];
    this.setData({ selectedPlan: plan, selectedPlanIndex: idx });
    this.loadPlanSchedules(plan);
  },
  loadPlanSchedules(plan) {
    wx.request({
      url: getApp().globalData.baseUrl + '/api/ride/plan/schedules',
      data: {
        userId: this.data.userId,
        startDate: plan.startTime,
        endDate: plan.endTime
      },
      success: res => {
        // 完全复用schedule页面的格式化逻辑
        const schedules = (res.data.data || []).map(item => {
          const arr = item.imageUrls
            ? item.imageUrls.split(',').map(url =>
                url.startsWith('http') ? url : `${getApp().globalData.baseUrl}${url}`
              )
            : [];
          let typeText = '';
          switch(Number(item.type)) {
            case 0: typeText = '酒店'; break;
            case 1: typeText = '饭店'; break;
            case 2: typeText = '景点'; break;
            case 3: typeText = '骑行'; break;
            default: typeText = '';
          }
          let timeText = item.datetime ? item.datetime.slice(11, 16) : '12:00';
          // 地图坐标处理
          let markerLat = item.lat;
          let markerLng = item.lng;
          // 如果是骑行类型且有rideList和rideId，优先用终点坐标（此处可根据实际数据结构补充）
          // 这里只能用item.lat/item.lng，除非你把rideList也查出来
          return {
            ...item,
            type: Number(item.type),
            typeText,
            timeText,
            imageUrlsArr: arr.length ? arr : [`/images/${item.type || 0}.jpg`],
            markerLat,
            markerLng
          };
        });
        // 按天分组
        const grouped = {};
        schedules.forEach(s => {
          const day = s.datetime.slice(0, 10);
          if (!grouped[day]) grouped[day] = [];
          grouped[day].push(s);
        });
        const planSchedules = Object.keys(grouped).sort().map(date => ({
          date,
          schedules: grouped[date].sort((a, b) => (a.datetime > b.datetime ? 1 : -1))
        }));
        this.setData({ planSchedules });
      }
    });
  }
}); 